package com.crm.controller.permission;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.crm.exception.ServiceException;
import com.crm.pojo.CrmDept;
import com.crm.pojo.Role;
import com.crm.pojo.Userinfo;
import com.crm.service.permission.GrantService;
import com.crm.vo.LoginVo;
import com.crm.vo.MenubarNode;
import com.crm.vo.Result;
import com.crm.vo.RidAndMids;
import com.crm.vo.RoleNode;
import com.crm.vo.UidAndRids;

import net.coobird.thumbnailator.Thumbnails;

@Controller
@SessionAttributes({ "userinfo", "mids" })
public class GrantController {

	@Autowired
	private GrantService grantService;

	/**
	 * 查找该用户的拥有角色
	 * 
	 * @param uId
	 * @return
	 */
	@GetMapping("get-Role-For-Grants")
	@ResponseBody
	public List<RoleNode> getRoleForGrants(Long uId) {
		return grantService.getRoleForGrant(uId);
	}

	/**
	 * 给指定用户赋予角色
	 * 
	 * @param ids
	 * @return
	 */
	@PostMapping("grant-Role-To-Users")
	@ResponseBody
	public Result grantRoleToUsers(UidAndRids ids) {
		try {
			grantService.grantRoleToUser(ids.getuId(), ids.getRids());
			return Result.SUCCESS;
		} catch (ServiceException e) {
			e.printStackTrace();
			return new Result(e);
		}
	}

	/**
	 * 查询该角色拥有的功能
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("get-Menubar-To-Grants")
	@ResponseBody
	public List<MenubarNode> getMenubarToGrants(Long id) {
		return grantService.getMenubarToGrant(id);
	}

	/**
	 * 给角色授权
	 * 
	 * @param rmids
	 * @return
	 */
	@PostMapping("grant-Menubar-To-Roles")
	@ResponseBody
	public Result grantMenubarToRoles(RidAndMids rmids) {
		try {
			grantService.grantMenubarToRole(rmids.getId(), rmids.getMids());
			return Result.SUCCESS;
		} catch (ServiceException e) {
			e.printStackTrace();
			return new Result(e);
		}
	}

	/**
	 * 登录
	 * 
	 * @param name
	 * @param pwd
	 * @param m
	 * @return
	 */
	@PostMapping("toLogins")
	@ResponseBody
	public Result toLogins(LoginVo lv, Model m) {
		try {
			Userinfo userinfo = grantService.toLogin(lv.getLogin(), lv.getPwd());
			if (userinfo != null) {
				m.addAttribute("userinfo", userinfo);
				m.addAttribute("mids", grantService.queryAllMidsByuId(userinfo.getUId()));
				return Result.SUCCESS;
			} else {
				return new Result("用户名或密码错误！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new Result("用户名或密码错误！");
		}
	}

	/**
	 * 注销用户
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@GetMapping("cancel-Login")
	@ResponseBody
	public Result cancelLogin(HttpServletRequest request, HttpSession httpSession) throws IOException {
		try {
			httpSession.removeAttribute("userinfo");
			return Result.SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			return new Result(e);
		}
	}

	@GetMapping("updateUserself")
	public String toUpdateUserself() {
		return "permission/update-userself";
	}

	/**
	 * 用户自己修改
	 * 
	 * @param uname
	 * @param upassword
	 * 
	 * @param urealName
	 * @param phone
	 * @param userAddress
	 * @param m
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@PostMapping("update-User-self")
	@ResponseBody
	public Result updateUserself(String uname, String upassword, String urealName, String phone, String userAddress,
			Model m) throws IllegalStateException, IOException {
		try {

			Userinfo userinfo = grantService.queryOneUsers(uname);
			userinfo.setUpassword(upassword);
			userinfo.setUrealName(urealName);
			userinfo.setPhone(phone);
			userinfo.setUserAddress(userAddress);
			grantService.updateOUserself(userinfo);

			if (userinfo != null) {
				m.addAttribute("userinfo", userinfo);
			}
			return Result.SUCCESS;

		} catch (Exception e) {
			e.printStackTrace();
			return new Result(e);
		}
	}

	/**
	 * 上传头像
	 * 
	 * @param uimage
	 * @param request
	 * @param m
	 * @return
	 * @throws IOException
	 */
	@PostMapping("upload-File")
	@ResponseBody
	public Result uploadFile(MultipartFile uimage, HttpServletRequest request, Model m) throws IOException {
		try {
			HttpSession session = request.getSession();
			Userinfo user = (Userinfo) session.getAttribute("userinfo");
			String uname = user.getUname();
			// 使用UUID重命名图片 避免重复
			String name = UUID.randomUUID().toString().replaceAll("-", "");
			// 获取文件扩展名
			String ext = FilenameUtils.getExtension(uimage.getOriginalFilename());
			// 设置图片上传路径
			String url = request.getSession().getServletContext().getRealPath("/touploads");
			File touploads = new File(url);
			if (!touploads.exists())
				touploads.mkdirs();

			String url2 = request.getSession().getServletContext().getRealPath("/touploads");
			File touploads2 = new File(url);
			if (!touploads2.exists())
				touploads2.mkdirs();
			String NewName = name + "." + ext;

			// 以绝对路径保存重命名后的图片
			uimage.transferTo(new File(url + "/" + name + "." + ext));
			Thumbnails.of(url + "\\" + NewName).size(50, 50).toFile(url2 + "\\" + NewName);

			Userinfo userinfo = grantService.queryOneUsers(uname);
			userinfo.setUimage("touploads/" + name + "." + ext);
			grantService.updateOUserself(userinfo);

			if (userinfo != null) {
				m.addAttribute("userinfo", userinfo);
			}
			return Result.SUCCESS;
		} catch (IllegalStateException e) {
			e.printStackTrace();
			return new Result(e);
		}

	}

	@GetMapping("uphead")
	public String toHeadUp() {
		return "permission/update-head";
	}
}
